package admin

import (
	"XSSS_v2/config"
	"XSSS_v2/handler"
	"XSSS_v2/model"
	"XSSS_v2/pkg/casbin"
	"XSSS_v2/pkg/errno"
	"github.com/gin-gonic/gin"
)

// Register
// @Summary 用户注册
// @Param admin body model.Admin true "admin info"
// @Produce json
// @Router /Register [post]
func Register(c *gin.Context) {

	var r RegisnerRequest
	//绑定
	err := c.Bind(&r)
	if err != nil {
		handler.SendResponse(c, errno.ErrBind, nil)
		return
	}

	//赋值对象
	admin := &model.Admin{
		BaseModel: model.BaseModel{Id: r.Id},
		Aname:     r.Username,
		Apwd:      r.Password,
	}

	//验证字段
	err = admin.Validate()
	if err != nil {
		handler.SendResponse(c, errno.ErrValidation, nil)
		return
	}

	//密码加密
	err = admin.Encrypt()
	if err != nil {
		handler.SendResponse(c, errno.ErrEncrypt, nil)
		return
	}

	//创建对象
	err = admin.CreateAdmin()
	if err != nil {
		handler.SendResponse(c, errno.ErrDatabase, nil)
		return
	}

	//返回响应
	rsp := RegisterResponse{
		Username: r.Username,
	}

	casbin.AddAdminUser(admin.Aname)

	config.Log.Infof("用户注册")
	handler.SendResponse(c, nil, rsp)

}
